import json
import os

default_filename = os.path.expanduser("~/.homeswitch")

class Settings:
	def __init__(self, filename=default_filename):
		self.filename = filename
		self.settings = {}
		self.load()
	
	def load(self):
		if not os.path.exists(self.filename):
			return
		
		fd = open(self.filename)
		for line in fd.readlines():
			key, val = line.split("=", 1)
			try:
				self.settings[key] = json.loads(val)
			except ValueError as ex:
				print "could read setting '%s'. Reason:" % key
				print ex
	
	def save(self):
		fd = open(self.filename, "w")
		for key,value in self.settings.items():
			fd.write("%s=%s\n" % (key, json.dumps(value)))
	
	def __getitem__(self, key):
		return self.settings[key]
	
	def __iter__(self):
		return self.settings.__iter__()
	
	def __setitem__(self, key, value):
		self.settings[key] = value
		self.save()
	
	def __delitem__(self, key, value):
		del self.settings[key]
		self.save()

